{extend name="admin@index_layout"/}
{block name="main"}
<style type="text/css">
.releasetips {position: relative;}
.releasetips i {display: block;background: #f00;border-radius: 50%;width: 0.3em;height: 0.3em;top: 0px;right: -8px;position: absolute;box-shadow: 0px 0px 2px #f11414;}
</style>
<div class="alert alert-info-light">
    <b>温馨提示</b><br>
    1、插件在线安装，升级和购买需要注册YznCMS官网账号,请点击下方【会员信息】，点击【注册】按钮<br>
    2、点击插件名称可查看详情，截图和日志等信息
</div>
{if $type=='online'}
<div class="layui-tab layui-tab-card" lay-filter="tabswitch" style="box-shadow: none;">
    <ul class="layui-tab-title nav-category">
        <li class="layui-this" data-id="">全部</li>
    </ul>
</div>
{/if}
<input type="hidden" name="category_id" value="0">
<div class="layui-card">
    <div class="layui-card-header">插件管理</div>
    <div class="layui-card-body">
        <table class="layui-hide" id="currentTable" lay-filter="currentTable"></table>
    </div>
</div>

<script type="text/html" id="titleTpl">
    <div>
    {{#  if(d.url){ }}
        {{#  if(d.name != 'recommend' ){ }}
        <a href="javascript:;" data-open="{{d.url}}" lay-tips="查看插件介绍和帮助" title="插件详情">{{= d.title }}</a>
        {{#  } else { }}
        <a href="{{= d.url}}" target="_blank" lay-tips="查看插件介绍和帮助">{{= d.title }}</a>
        {{#  } }}
    {{#  } else { }}
        <a href="javascript:;">{{= d.title }}</a>
    {{#  } }}
    </div>
</script>

<script type="text/html" id="operateTpl">
{{#  if(d.addon){ }}
    {{# if(d.addon.version!=d.version){ }}
        {{# if(typeof d.releaselist !="undefined" && d.releaselist.length>1){ }}
        <a class="layui-btn layui-btn-xs layui-btn-normal" data-name="{{d.name}}" data-version="{{d.version}}" data-title="{{d.title}}"  data-value="{{= JSON.stringify(d.releaselist)}}" lay-event="upgrade">升级 <i class="layui-icon layui-icon-down"></i></a>
        {{# }else if(typeof d.releaselist !="undefined" && d.releaselist.length>0){ }}
        <a class="layui-btn layui-btn-xs layui-btn-normal btn-upgrade" data-name="{{d.name}}" data-version="{{d.version}}" data-title="{{d.title}}">升级</a>
        {{#  } }}
    {{#  } }}

    {{#  if(d.addon.config == 1 ){ }}
    <a class="layui-btn layui-btn-xs" data-open='{:url("config")}?name={{d.name}}' title="插件设置 -【{{d.title}}】">设置</a>
    {{#  } }}

    <a class="layui-btn layui-btn-xs layui-btn-danger btn-uninstall" data-name="{{d.name}}" data-status="{{d.addon.status}}"  data-title="确定卸载【{{d.title}}】，进行该操作？" confirm>卸载</a>
{{#  } else { }}
    {{# if(typeof d.releaselist !="undefined" && d.releaselist.length>1){ }}
    <a class="layui-btn layui-btn-xs" data-name="{{d.name}}" data-version="{{d.version}}" data-title="确定安装【{{d.title}}】，进行该操作？"  data-value="{{= JSON.stringify(d.releaselist)}}" lay-event="install">安装 <i class="layui-icon layui-icon-down"></i></a>
    {{# }else if(typeof d.releaselist !="undefined" && d.releaselist.length>0){ }}
    <a class="layui-btn layui-btn-xs btn-install" data-name="{{d.name}}" data-version="{{d.version}}" data-title="确定安装【{{d.title}}】，进行该操作？">安装</a>
    {{#  } }}

    {{# if(d.button){ }}
        <a href="{{d.url}}" class="layui-btn layui-btn-xs layui-btn-normal" target="_blank">
            {{d.button}}
        </a>
    {{#  } }}
{{#  } }}
</script>

<script id="statusTpl" type="text/html">
{{#  if(d.addon){ }}
    <input type="checkbox" value="{{= d.id }}" title="启用|禁用" lay-skin="switch" lay-filter="templet-status" data-name="{{d.name}}" data-action="{{= d.addon.status == 1 ? "disable" : "enable"}}" {{= d.addon.status == 1 ? "checked" : "" }}>
{{#  } }} 
</script>

<script id="conflicttpl" type="text/html">
    <div class="alert alert-danger-light">
        <strong>温馨提示</strong><br>
        此插件中发现和现有系统中部分文件发现冲突！以下文件将会被影响，请备份好相关文件后再继续操作
    </div>
    <table class="layui-table">
        <thead>
        <tr>
            <th>#</th>
            <th>文件</th>
        </tr>
        </thead>
        <tbody>
        {{# for(var i=0;i < d.list.conflictlist.length;i++){ }}
        <tr>
            <th scope="row">{{i+1}}</th>
            <td>{{d.list.conflictlist[i]}}</td>
        </tr>
        {{#  }; }}
        </tbody>
    </table>
</script>

<script id="uninstalltpl" type="text/html">
    <div class="">
        <div class="">{{ d.title }}
            <p class="text-danger">卸载将会删除所有插件文件且不可找回!!! </p>
            {if config('app_debug')}
            <p class="text-danger"><input type="checkbox" name="droptables" id="droptables" data-name="{{ d.name }}"/> 删除所有插件相关数据表且不可找回!!! </p>
            {/if}
            <p class="text-danger">如有重要数据请备份后再操作!!!</p>
        </div>
    </div>
</script>

<script id="logintpl" type="text/html">
    <div>
        <form class="layui-form">
            <div class="alert alert-danger-light">
                <strong>温馨提示</strong><br/>此处登录账号为<a href="https://www.yzncms.com" target="_blank">Yzncms官网账号</a>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-wrap">
                    <div class="layui-input-prefix">
                      <i class="layui-icon layui-icon-username"></i>
                    </div>
                    <input type="text" class="layui-input" id="inputAccount" value="" autocomplete="off" placeholder="你的手机号、用户名或邮箱">

                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-wrap">
                    <div class="layui-input-prefix">
                      <i class="layui-icon layui-icon-password"></i>
                    </div>
                    <input type="password" class="layui-input" id="inputPassword" value="" autocomplete="off" lay-affix="eye" placeholder="你的密码">

                </div>
            </div>
        </form>
    </div>
</script>

<script id="userinfotpl" type="text/html">
    <div>
        <form class="form-horizontal form-userinfo">
            <div class="alert alert-dismissable alert-info-light">
                <strong>温馨提示</strong><br/>你好！{{d.username}}<br />当前你已经登录，将同步保存你的购买记录
            </div>
        </form>
    </div>
</script>
{/block}
{block name="script"}
<script>
layui.use(['yznTable','table','laytpl','yzn','notice','element','dropdown','form','yznUpload'], function() {
    var yznTable = layui.yznTable,
        $ = layui.$,
        table = layui.table,
        laytpl = layui.laytpl,
        yzn = layui.yzn,
        notice = layui.notice,
        element = layui.element,
        dropdown = layui.dropdown,
        form = layui.form,
        yznUpload = layui.yznUpload;

    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTable',
        layFilter: 'currentTable_LayFilter',
    };

    var area = [$(window).width() > 800 ? '800px' : '95%', $(window).height() > 600 ? '600px' : '95%'];

    var switch_local = function () {
        layer.confirm('插件市场暂不可用，是否切换到本地插件？', {
            title: '温馨提示',
            btn: ['切换到本地插件', '重新尝试加载']
        }, function (index) {
            layer.close(index);
            $(".btn-switch[data-type='local']")[0].click();
        }, function (index) {
            layer.close(index);
            table.reload(init.table_render_id);
        });
        return false;
    };

    yznTable.render({
        init: init,
        toolbar: ['refresh',
            [{
                html:'<a id="faupload-addon" class="layui-btn layui-btn-sm faupload" data-url="{:url("local")}" data-chunking="false" data-mimetype="zip,fastaddon" data-multiple="false"><i class="iconfont icon-upload-fill"></i>&nbsp;本地安装</a>'
             },{
                html:'<a class="layui-btn {if $type=='online'}layui-btn-normal{else}layui-btn-primary layui-border-blue{/if} layui-btn-sm btn-switch" data-type="all" href="{:url("index")}" style="margin-left: 10px !important;"><i class="iconfont icon-other"></i>&nbsp;全部</a>'
             },{
                html:'<a class="layui-btn {if $type=='local'}layui-btn-normal{else}layui-btn-primary layui-border-blue{/if} layui-btn-sm btn-switch" data-type="local" href="{:url("index",["type"=>"local"])}"><i class="iconfont icon-manage"></i>&nbsp;本地插件</a>'
             },{
                html:'<a class="layui-btn layui-bg-black layui-btn-sm btn-userinfo" style="margin-left: 10px !important;" href="javascript:;"><i class="iconfont icon-user-line"></i>&nbsp;会员信息</a>'
             }
            ],
        ],
        url: '{:url("index",["type"=>$type])}',
        css :'.layui-table-tool-temp{padding-right: 85px;}',
        showSearch:false,
        cols: [
            [
                { field: 'title', width: 200, title: '名称',templet: '#titleTpl'},
                { field: 'name', width: 150, title: '标识' },
                { field: 'description', title: '描述' },
                { field: 'author', width: 90, title: '作者' },
                {if $type == 'online'}
                { field: 'price', width: 95, title: '价格' , templet: function(d){
                    if (isNaN(d.price)) {
                        return d.price;
                    }
                    return parseFloat(d.price) == 0 ? '<span class="text-success">' + '免费' + '</span>' : '<span class="text-danger">￥' + d.price + '</span>';
                }},
                { field: 'downloads', width: 90, title: '下载' },
                {/if}
                { field: 'version', width: 80, title: '版本',templet: function(d){
                    return d.addon && d.addon.version != d.version ? '<a href="javascript:;"><span class="releasetips text-primary" lay-tips="发现新版本:'+d.version+'">' + d.addon.version + '<i></i></span></a>' : d.version;
                }},
                { field: 'status', width: 90, title: '状态', templet: '#statusTpl' },
                { fixed: 'right', width: 180, title: '操作', templet: '#operateTpl' }
            ]
        ],
        page: {limit:20},
        before(){
          let userinfo = yzn.cache.getStorage('yzncms_userinfo');

          this.where.uid = userinfo ? userinfo.id : '';
          this.where.token = userinfo ? userinfo.token : '';
          this.where.category_id = $('input[name="category_id"]').val();
        },
        done: function(res, curr, count){
            if (res && typeof res.category != 'undefined' && $(".nav-category li").length == 1) {
                $.each(res.category, function (i, j) {
                    $("<li data-id='" + j.id + "'>" + j.title + "</li>").insertAfter($(".nav-category li:first"));
                });
            }
            if(count==-1){
                switch_local();
            }
            yznUpload.api.upload("#faupload-addon", function (data, ret) {
                //上传完毕回调
                var addon = data.addon;
                var testdata = data.addon.testdata;
                operate(addon.name, 'enable', false, function (data, ret) {
                    layer.alert('安装成功！清除浏览器缓存和框架缓存后生效！' + (testdata ? '<br>你还可以继续导入测试数据！' : ""), {
                        btn: testdata ? ['导入测试数据', '暂不导入'] : ['确定'],
                        title:'温馨提示',
                        yes: function (index) {
                            if (testdata) {
                                yzn.request.post({
                                    url: '{:url("testdata")}',
                                    data: {
                                        name: addon.name,
                                    }
                                }, function (data,res) {
                                    layer.close(index);
                                    yzn.msg.success(res.msg);
                                });
                            } else {
                                layer.close(index);
                            }
                        },
                        icon: 1
                    });
                });  
                return false;
            }, function (data, ret) {
                if (ret.msg && ret.msg.match(/(login|登录)/g)) {
                    return layer.alert(ret.msg, {
                        title: '温馨提示',
                        btn: ['立即登录'],
                        yes: function (index, layero) {
                            $(".btn-userinfo").trigger("click");
                        }
                    });
                }
            })
        }
    });

    yznTable.bindevent();

    // 检测是否登录
    $(document).on("mousedown", "#faupload-addon", function (e) {
        if(!isLogin()) return
    });


    table.on('tool('+init.layFilter+')', function(obj){
        var that = this;
        jsondata = $(this).data('value');
        var name = $(this).data("name");
        var title = $(this).data("title");
        const arr = jsondata.map(({id, version}) => ({ id, title: version }))

        dropdown.render({
            elem: that,
            show: true, // 外部事件触发即显示
            data: arr,
            click: function(data, othis){

                if(!isLogin()) return

                if(obj.event === 'install'){
                    yzn.msg.confirm(title, function(index){
                        install(name, data.title, false);
                    });
                }
                if(obj.event === 'upgrade'){
                    layer.confirm('确认升级<b>《'+title+'》</b>？<p class="text-danger">1、请务必做好代码和数据库备份！备份！备份！<br>2、升级后如出现冗余数据，请根据需要移除即可!<br>3、不建议在生产环境升级，请在本地完成升级测试</p>如有重要数据请备份后再操作！', function (index, layero) {
                        upgrade(name, data.title);
                    });
                }
            }
        })
    })


    element.on('tab(tabswitch)', function(data){
      var value = $(this).data("id");
      $('input[name="category_id"]').val(value);
      table.reload(init.table_render_id);
    });

    // 会员信息
    $(document).on("click", ".btn-userinfo", function (e, name, version) {
        var that = this;
        var area = [$(window).width() > 800 ? '500px' : '95%', $(window).height() > 600 ? '400px' : '95%'];
        var userinfo = yzn.cache.getStorage('yzncms_userinfo');
        if (!userinfo) {
            layer.open({
                content: laytpl($("#logintpl").html()).render({}),
                zIndex: 99,
                area: area,
                title: '登录',
                resize: false,
                btn: ['登录', '注册'],
                yes: function (index, layero) {
                    yzn.request.post({
                        url: '{$api_url}/member/login',
                        type: 'post',
                        data: {
                            account: $("#inputAccount", layero).val(),
                            password: $("#inputPassword", layero).val(),
                        }
                    }, function (data, ret) {
                        yzn.cache.setStorage('yzncms_userinfo',data.userinfo);
                        layer.closeAll();
                        layer.alert(ret.msg, {title: '温馨提示', icon: 1});
                        return false;
                    }, function (data, ret) {
                        notice.error({ message: ret.msg });
                    });
                },
                btn2: function () {
                    return false;
                },
                success: function (layero, index) {
                    this.checkEnterKey = function (event) {
                        if (event.keyCode === 13) {
                            $(".layui-layer-btn0").trigger("click");
                            return false;
                        }
                    };
                    $(document).on('keydown', this.checkEnterKey);
                    $(".layui-layer-btn1", layero).prop("href", "https://www.yzncms.com/member/index/register.html").prop("target", "_blank");
                },
                end: function () {
                    $(document).off('keydown', this.checkEnterKey);
                }
            });
        } else {
            yzn.request.post({
                url: '{$api_url}/member/index',
                data: {
                    uid: userinfo.id,
                    token: userinfo.token,
                }
            }, function (data) {
                layer.open({
                    content: laytpl($("#userinfotpl").html()).render(userinfo),
                    area: area,
                    title: '会员信息',
                    resize: false,
                    btn: ['退出登录', '关闭'],
                    yes: function () {
                        yzn.request.post({
                            url: '{$api_url}/member/logout',
                            data: {uid: userinfo.id, token: userinfo.token}
                        }, function (data, ret) {
                            yzn.cache.setStorage('yzncms_userinfo','');
                            layer.closeAll();
                            layer.alert(ret.msg, {title: '温馨提示', icon: 0});
                        }, function (data, ret) {
                            yzn.cache.setStorage('yzncms_userinfo','');
                            layer.closeAll();
                            layer.alert(ret.msg, {title: '温馨提示', icon: 0});
                        });
                    }
                });
                return false;
            }, function (data) {
                yzn.cache.setStorage('yzncms_userinfo','');
                $(that).trigger('click');
                return false;
            });

        }
    });

    var install = function (name, version, force) {
        var userinfo = yzn.cache.getStorage('yzncms_userinfo');
        var uid = userinfo ? userinfo.id : 0;
        var token = userinfo ? userinfo.token : '';
        yzn.request.post({
            url: '{:url("install")}',
            data: {
                name: name,
                force: force ? 1 : 0,
                uid: uid,
                token: token,
                version: version
            },
        }, function(data,res) {
            layer.closeAll();
            layer.alert('安装成功！清除浏览器缓存和框架缓存后生效！' + (data.addon.testdata ? '<br>你还可以继续导入测试数据！' : ""), {
                btn: data.addon.testdata ? ['导入测试数据', '暂不导入'] : ['确定'],
                title:'温馨提示',
                yes: function (index) {
                    if (data.addon.testdata) {
                        yzn.request.post({
                            url: '{:url("testdata")}',
                            data: {
                                name: name,
                            }
                        }, function (data,res) {
                            layer.close(index);
                            yzn.msg.success(res.msg);
                        });
                    } else {
                        layer.close(index);
                    }
                    table.reload(init.table_render_id);
                },
                icon: 1
            });
        },function(data,res) {
            var area = [$(window).width() > 650 ? '650px' : '95%', $(window).height() > 710 ? '710px' : '95%'];
            if (res && res.code === -2) {
                layer.closeAll();
                yzn.open('立即支付' , res.data.payurl,'','', {
                    area: area,
                    end: function () {
                        yzn.request.post({
                            url: '{:url("isbuy")}',
                            data: {
                                name: name,
                                force: force ? 1 : 0,
                                uid: uid,
                                token: token,
                                version: version
                            }
                        }, function () {
                            top.layer.alert('购买成功！请点击继续安装按钮完成安装！', {
                                btn: ['继续安装'],
                                title: '温馨提示',
                                icon: 1,
                                yes: function (index) {
                                    top.layer.close(index);
                                    install(name, version);
                                }
                            });
                            return false;
                        }, function () {
                            console.log('已取消');
                            return false;
                        });
                    }
                });
            }else if (res && res.code === -3) {
                //插件目录发现影响全局的文件
                layer.open({
                    content: laytpl($("#conflicttpl").html()).render({list:res.data}),
                    shade: 0.8,
                    area: area,
                    title:'温馨提示',
                    btn: ['继续操作', '取消'],
                    end: function () {

                    },
                    yes: function () {
                        install(name, version, true);
                    }
                });
            } else {
                layer.alert(res.msg, {title: '温馨提示', icon: 0});
            }
            return false;
        })
    }

    var uninstall = function (name, force, droptables) {
        yzn.request.post({
            url: '{:url("uninstall")}',
            data: {name: name, force: force ? 1 : 0, droptables: droptables ? 1 : 0}
        }, function (data,res) {
            layer.closeAll();
            yzn.msg.success(res.msg);
            table.reload(init.table_render_id);
        }, function (data,res) {
            if (res && res.code === -3) {
                //插件目录发现影响全局的文件
                layer.open({
                    content: laytpl($("#conflicttpl").html()).render({list:res.data}),
                    shade: 0.8,
                    area: area,
                    title:'温馨提示',
                    btn: ['继续操作', '取消'],
                    end: function () {

                    },
                    yes: function () {
                        uninstall(name, true, droptables);
                    }
                });
            } else {
                layer.alert(res.msg, {title: '温馨提示', icon: 0});
            }
            return false;
        });
    };

    // 点击升级
    $(document).on("click", ".btn-upgrade", function () {
        var name = $(this).data('name');
        var version = $(this).data("version");
        var title = $(this).data("title");

        if(!isLogin()) return

        layer.confirm('确认升级<b>《'+title+'》</b>？<p class="text-danger">1、请务必做好代码和数据库备份！备份！备份！<br>2、升级后如出现冗余数据，请根据需要移除即可!<br>3、不建议在生产环境升级，请在本地完成升级测试</p>如有重要数据请备份后再操作！', function (index, layero) {
            upgrade(name, version);
        });
    });

    var upgrade = function (name, version) {
        var userinfo = yzn.cache.getStorage('yzncms_userinfo');
        var uid = userinfo ? userinfo.id : 0;
        var token = userinfo ? userinfo.token : '';

        yzn.request.post({
            url: '{:url("upgrade")}',
            data: {
                name: name,
                uid: uid,
                token: token,
                version: version
            }
        }, function (data, ret) {
            table.reload(init.table_render_id);
            notice.success({ message: ret.msg });
            layer.closeAll();
        }, function (data, ret) {
            layer.alert(ret.msg, {title: '温馨提示'});
            return false;
        });
    };

    var operate = function (name, action, force, success) {
        yzn.request.post({
            url: '{:url("state")}',
            data: {name: name, action: action, force: force ? 1 : 0}
        }, function(data,res) {
            layer.closeAll();
            if (typeof success === 'function') {
                success(res);
            }
            table.reload(init.table_render_id);
            return false;   
        }, function(data,res) {
            if (res && res.code === -3) {
                //插件目录发现影响全局的文件
                layer.open({
                    content: laytpl($("#conflicttpl").html()).render({list:res.data}),
                    shade: 0.8,
                    area: area,
                    title:'温馨提示',
                    btn: ['继续操作', '取消'],
                    end: function () {

                    },
                    yes: function () {
                        operate(name, action, true, success);
                    }
                });
            } else {
                layer.alert(res.msg, {title: '温馨提示', icon: 0});
            }
        })
    };

    var isLogin = function (){
        var userinfo = yzn.cache.getStorage('yzncms_userinfo');
        var uid = userinfo ? userinfo.id : 0;

        if (parseInt(uid) === 0) {
            layer.alert('你当前未登录Yzncms，请登录后操作！', {
                title: '温馨提示',
                btn: ['立即登录'],
                yes: function (index, layero) {
                    $(".btn-userinfo").trigger("click");
                },
            });
            return false;
        }
        return true;
    }

    var tables = [];
    $(document).on("click", "#droptables", function () {
        if ($(this).prop("checked")) {
            yzn.request.post({
                url: '{:url("get_table_list")}',
                async: false,
                data: {name: $(this).data("name")}
            }, function (res) {
                tables = res.tables;
                return false;
            });
            var html;
            html = tables.length > 0 ? '<div class="alert alert-warning-light droptablestips" style="max-width:480px;max-height:300px;overflow-y: auto;">以下插件数据表将会被删除：<br>' + tables.join("<br>") + '<br>注意：部分插件还同时会删除演示数据和关联表等</div>'
                : '<div class="alert alert-warning-light droptablestips">注意：部分插件还同时会删除演示数据和关联表等</div>';
            $(html).insertAfter($(this).closest("p"));
        } else {
            $(".droptablestips").remove();
        }
        $(window).resize();
    });

    // 点击安装
    $(document).on("click", ".btn-install", function () {
        var name = $(this).data("name");
        var title = $(this).data("title");
        var version = $(this).data("version");
        
        if(!isLogin()) return

        yzn.msg.confirm(title, function(index){
            install(name, version, false);
        });
    });
    
    // 点击启用/禁用
    form.on('switch(templet-status)', function (obj) {
        var name = $(this).data("name");
        var action = $(this).data("action");
        $(this).trigger('click');
        form.render('checkbox');
        operate(name, action, false);
    })

    // 点击卸载
    $(document).on("click", ".btn-uninstall", function () {
        var name = $(this).data('name');
        var title = $(this).data('title');
        if ($(this).data('status') == 1) {
            layer.alert('请先禁用插件再进行卸载', {icon: 7});
            return false;
        }
        yzn.msg.confirm(laytpl($("#uninstalltpl").html()).render({name:name,title:title}), function (index, layero) {
            uninstall(name, false, $("input[name='droptables']", layero).prop("checked"));
        });
    });

});
</script>
{/block}